<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>this的显式绑定</title>
</head>

<body>

</body>
<script>
  // call()、apply()、bind()把对象绑定到this上，叫做显式绑定
  var a = 0;
  function foo() {
    console.log(this.a);
  }
  var obj = {
    a: 2
  }
  foo(); //0
  foo.call(obj);  //2
  foo.apply(obj); //2
  var fn = foo.bind(obj);
  fn(); //2

  // 2、硬绑定，是显式绑定的一个变种，使得this不能再被改变
  var a = 0;
  function foo() {
    console.log(this.a);
  }
  var obj = {
    a: 2
  }
  var bar = function () {
    foo.call(obj);
  }
  bar();  //2
  setTimeout(bar, 1000);  //2
  bar.call(window); //2

  // 3、数组的forEach(fn,对象)、map()、filter()、some()、every()
  var id = 'window';
  /* function fn(el) {
    console.log(el, this.id);
  } */
  var obj = {
    id: 'fn'
  }
  var arr = [1, 2, 3];
  // this 指向了 obj
  arr.forEach(function (el, index) {
    console.log(el, index, this);
  }, obj)















</script>

</html>